package br.com.alexgirao.racha.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import br.com.alexgirao.racha.modelo.BaseModelo;
import br.com.alexgirao.racha.util.ConstantesRachaCore;
import br.com.alexgirao.racha.vo.BaseVO;

public abstract class BaseRepository {
	
	protected EntityManager manager;
	
	public BaseRepository() {
		manager = 
		Persistence.createEntityManagerFactory(ConstantesRachaCore.PERSISTENCE_UNIT).
		createEntityManager();
	}
	
	protected void iniciarTransacao(){
		manager.getTransaction().begin();
	}
	
	protected void encerrarTransacao(){
		manager.getTransaction().commit();
	}
	
	public void salvar(BaseModelo m){
		try{
			iniciarTransacao();
			if(m.getId()==null){
				manager.persist(m);//novo
			}else{
				manager.merge(m);//alterar
			}
			encerrarTransacao();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public void remover(BaseModelo m){
		try{
			iniciarTransacao();
			manager.remove(m);
			encerrarTransacao();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public void buscarPorId(BaseModelo m){
		try{
			iniciarTransacao();
			manager.find(BaseModelo.class, m.getId());
			encerrarTransacao();
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public abstract List<?> buscarTodos();
	
	public abstract List<?> buscarPorFiltro(BaseVO vo);

}
